import os
from datetime import datetime
import sys

class Log():
    def __init__(self,):
        self._checkLogDirectory()
        self.file = self._getLogFilePath()


    def _checkLogDirectory(self):
        # 获取当前执行文件的路径
        path = os.path.abspath(sys.executable)

        # 获取文件名
        filename = os.path.basename(path)
        
        # 执行文件目录
        currentDirectory = os.path.dirname(path)

        # 判断执行文件名是否以 'python.exe' 结尾
        if filename == 'python.exe':
            # 获取当前文件的目录
            currentDirectory = os.path.dirname(os.path.abspath(__file__))
            # 源码测试 日志目录
            currentDirectory = os.path.dirname(currentDirectory)

        # 日志目录
        self.logDirectory = currentDirectory + '\\Log'
        # 检查目录是否存在
        if not os.path.exists(self.logDirectory):
            # 创建目录
            os.makedirs(self.logDirectory)


    def _getLogFilePath(self):
        now = datetime.now()
        # 格式化为字符串
        formatted_now = now.strftime("%Y-%m-%d_%H-%M-%S")
        filePath = self.logDirectory + '\\' + formatted_now + '.log'
        return filePath
    

    def append(self,text:str):
        # 打开文件以写入
        with open(self.file, 'a') as file:
            # 写入文本
            file.write(text + '\n')